package com.springcloud.demo.dynamicTable.dynamic.controller;

import com.springcloud.demo.dynamicTable.dynamic.entity.MetaInfoDO;
import com.springcloud.demo.dynamicTable.dynamic.entity.TableInfoEntity;
import com.springcloud.demo.dynamicTable.dynamic.entity.UpdateEntity;
import com.springcloud.demo.dynamicTable.dynamic.service.DynamicService;
import com.springcloud.demo.dynamicTable.dynamic.service.MetaInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhouyang
 * @Description
 * @date 2018/08/13
 */
@RestController
public class DynamicController {

    @Autowired
    DynamicService dynamicService;

    @Autowired
    MetaInfoService metaInfoService;

    @GetMapping("hello")
    public String hello(){
        return "hello,world~~~~~~~~~~~~~~~~";
    }

    /**
     * @param values ：新增字段的值
     * @param tableName ： 表名
     * @return
     */
    @PostMapping("/save/{tableName}")
    public Object save(@RequestBody Map<String, Object> values, @PathVariable(value = "tableName")String tableName){
        //获取对应表格字段元信息
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("tablename", tableName);
        List<MetaInfoDO> list = metaInfoService.list(queryMap);
        List<String> columnList = list.stream().map(x -> x.getColumnname()).collect(Collectors.toList());
        //转换实体类
        TableInfoEntity tableInfoEntity = new TableInfoEntity();
        tableInfoEntity.setTableName(tableName);
        tableInfoEntity.setColumnameList(columnList);
        //新增
        dynamicService.save(tableInfoEntity, values);
        return  "success";
    }

    /**
     *
     * @param updateEntity ：更新的信息
     * @param tableName ： 表名
     * @return
     */
    @PutMapping("/update/{tableName}")
    public Object update(@RequestBody UpdateEntity updateEntity, @PathVariable(value = "tableName")String tableName){
        //获取对应表格字段元信息
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("tablename", tableName);
        List<MetaInfoDO> list = metaInfoService.list(queryMap);
        List<String> columnList = list.stream().map(x -> x.getColumnname()).collect(Collectors.toList());
        //转换实体类
        TableInfoEntity tableInfoEntity = new TableInfoEntity();
        tableInfoEntity.setTableName(tableName);
        tableInfoEntity.setColumnameList(columnList);
        //更新
        dynamicService.update(tableInfoEntity, updateEntity.getValues(), updateEntity.getParams());
        return "success";
    }

}
